import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { AllExceptionFilter } from './common/filters/all-exception.filter';
import { VERSION_NEUTRAL, VersioningType } from '@nestjs/common';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    const configService = app.get(ConfigService);
    const port = configService.get<number>('PORT', 3000);
    const cors = configService.get<string>('CORS') === 'true';
    const prefix = configService.get<string>('PREFIX', '/api');
    const version = configService.get<string>('VERSION');
    let versions: string[] = [];
    if (version && version.length > 0 && version.indexOf(',') > 0) {
        versions = version.split(',');
    }
    const errfilterFlag = configService.get<string>('ERROR_FILTER') === 'true';
    app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
    app.setGlobalPrefix(prefix);
    app.enableVersioning({ type: VersioningType.URI, defaultVersion: typeof versions === 'undefined' ? VERSION_NEUTRAL : versions });
    if (cors) {
        app.enableCors();
    }
    if (errfilterFlag) {
        const httpAdapter = app.get(HttpAdapterHost);
        app.useGlobalFilters(new AllExceptionFilter(httpAdapter));
    }
    console.log(`Server listening on port ${port}`);
    await app.listen(port);
}
void bootstrap();
